package com.szgd.service.personnel;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.http.HttpSession;

import com.szgd.bean.Certificate;
import com.szgd.util.*;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.szgd.bean.SysDict;
import com.szgd.dao.ecdata.personnel.PersonnelInfoMapper;
import com.szgd.paging.Order;
import com.szgd.paging.PageBounds;
import com.szgd.service.gatherEquip.GatherEquipService;
import com.szgd.service.sys.DeptService;
import com.szgd.service.sys.SimulateBaseService;
import com.szgd.service.sys.SysDictService;
import org.springframework.web.multipart.MultipartFile;

@Service
public class PersonnelInfoService extends SimulateBaseService {

    @Autowired
    PersonnelInfoMapper personnelInfoMapper;
    @Autowired
    DeptService deptService;
    @Autowired
    SysDictService sysDictService;
    @Autowired
    GatherEquipService gatherEquipService;
    @Autowired
    PersonnelGatherEquipService personnelGatherEquipService;
    @Autowired
    CertificateService certificateService;
    @Autowired
    AttachService attachService;
    @Autowired
    FileUtil fileUtil;

    private static Logger logger = Logger.getLogger(PersonnelInfoService.class);

    public List<Map<String, Object>> getPersonnelInfoListNoPage(Map<String, Object> params) {

        List<Map<String, Object>>  personnelInfoList = personnelInfoMapper.getPersonnelInfoList(params);
        if (personnelInfoList != null)
        {
            String uploadPath = PropertiesUtil.get("uploadPath");
            for (int i = 0; i < personnelInfoList.size(); i++) {
                Map<String, Object> personnelInfoMap = personnelInfoList.get(i);
                String path = personnelInfoMap.get("path")==null?"":personnelInfoMap.get("path").toString();
                String fileName = personnelInfoMap.get("fileName")==null?"":personnelInfoMap.get("fileName").toString();
                String fullPath = uploadPath + File.separator + path +  File.separator + fileName;
                personnelInfoMap.put("fullPath",fullPath);
            }
        }
        return personnelInfoList;
    }

    public List<Map<String, Object>> getPersonnelInfoList(Map<String, Object> params) {
        String sortColumn = "ID"; //默认的排序列
        String sortType = "DESC";
        String iSortCol_0 = (String) params.get("iSortCol_0");	//排序字段，前台传进来的为数值，列从0开始
        String sSortDir_0 = (String) params.get("sSortDir_0");	//排序类型，asc或desc
        if(StringUtil.isNotBlank(iSortCol_0) && StringUtil.isNotBlank(sSortDir_0)){
            sortColumn = (String) params.get("mDataProp_" + iSortCol_0);
            sortType = sSortDir_0;
        }
        String sortString = sortColumn + "." + sortType;	//排序字段及排序类型
        PageBounds pageBounds = new PageBounds(params, Order.formString(sortString));	//绑定排序及相关参数
        List<Map<String, Object>>  personnelInfoList = getSqlSession().selectList("com.szgd.dao.ecdata.personnel.PersonnelInfoMapper.getPersonnelInfoList", params,pageBounds);
        if (personnelInfoList != null)
        {
            String uploadPath = PropertiesUtil.get("uploadPath");
            for (int i = 0; i < personnelInfoList.size(); i++) {
                Map<String, Object> personnelInfoMap = personnelInfoList.get(i);
                String path = personnelInfoMap.get("path")==null?"":personnelInfoMap.get("path").toString();
                String fileName = personnelInfoMap.get("fileName")==null?"":personnelInfoMap.get("fileName").toString();
                String fullPath = uploadPath + File.separator + path +  File.separator + fileName;
                personnelInfoMap.put("fullPath",fullPath);
            }
        }
        return personnelInfoList;
    }

    public Map<String, Object> getPersonnelInfo(Map<String, Object> params) {
        List<Map<String,Object>>  list = personnelInfoMapper.getPersonnelInfo(params);
        if (list != null && list.size() >0)
        {
            return  list.get(0);
        }
        else
            return  null;
    }

    public Map<String, Object> getPersonnelInfoByPersonId(Map<String, Object> params) {
        List<Map<String,Object>>  list = personnelInfoMapper.getPersonnelInfoByPersonId(params);
        if (list != null && list.size() >0)
        {
            return  list.get(0);
        }
        else
            return  null;
    }

    public Map<String, Object> getPersonnelInfo(String id, Integer userId) {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("id",id);
        paramsMap.put("userId",userId);
        List<Map<String,Object>> personnelInfoList = personnelInfoMapper.getPersonnelInfoList(paramsMap);
        if (personnelInfoList == null || personnelInfoList.size() == 0)
            return null;
        return personnelInfoList.get(0);
    }

    public boolean isHaveSamePersonnelInfo(String name,String idNumber) {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("name",name);
        paramsMap.put("idNumber",idNumber);
        List<Map<String,Object>>  list = personnelInfoMapper.getPersonnelInfo(paramsMap);
        if (list != null && list.size() >0)
        {
            return  true;
        }
        else
            return  false;
    }

    public boolean isHaveSamePersonnelInfoByIdNumber(String idNumber) {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("idNumber",idNumber);
        List<Map<String,Object>>  list = personnelInfoMapper.getPersonnelInfo(paramsMap);
        if (list != null && list.size() >0)
        {
            return  true;
        }
        else
            return  false;
    }

    public Map<String, Object> getPersonnelInfoByIdNumber(String idNumber) {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("idNumber",idNumber);
        List<Map<String,Object>>  list = personnelInfoMapper.getPersonnelInfo(paramsMap);
        if (list != null && list.size() >0)
        {
            return  list.get(0);
        }
        else
            return  null;
    }

    public void insertPersonnelInfo(Map<String, Object> paramsMap) {

        personnelInfoMapper.insertPersonnelInfo(paramsMap);
    }

    public void updatePersonnelInfo(Map<String, Object> paramsMap) {

        personnelInfoMapper.updatePersonnelInfo(paramsMap);
    }

    public void updateOtherSystemId(Map<String, Object> paramsMap) {

        personnelInfoMapper.updateOtherSystemId(paramsMap);
    }
    public void updatePersonId(Map<String, Object> paramsMap) {

        personnelInfoMapper.updatePersonId(paramsMap);
    }
    public void updateFaceId(Map<String, Object> paramsMap) {

        personnelInfoMapper.updateFaceId(paramsMap);
    }

    public void deletePersonnelInfo(Map<String, Object> paramsMap) {

        personnelInfoMapper.deletePersonnelInfo(paramsMap);
    }

    public void updateBidCount(String id,int bidCount) {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("id",id);
        paramsMap.put("bidCount",bidCount);
        personnelInfoMapper.updateBidCount(paramsMap);

    }


    public Map<String, Object> batchImportPersonnelInfo(List<Map<String, Object>> personnelInfoList,String userId,String batchNo) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> successList = new ArrayList<>();   //记录导入成功的数据
        List<Map<String, Object>> updateList = new ArrayList<>();   //记录更新的数据
        List<Map<String, Object>> failedList = new ArrayList<>();   //记录导入失败的数据
        List<Map<String, Object>> ignoreList = new ArrayList<>();   //记录忽略的数据
        Map<String, Object> certificateMap = new HashMap<>();

        for (Map<String, Object> personnelInfoMap : personnelInfoList) {

            certificateMap.put("number",personnelInfoMap.get("number"));
            certificateMap.put("name",personnelInfoMap.get("certificateName"));
            certificateMap.put("certificateType",personnelInfoMap.get("certificateType"));
            certificateMap.put("issueName",personnelInfoMap.get("issueName"));
            certificateMap.put("effectiveEndDate",personnelInfoMap.get("effectiveEndDate"));

            HashMap<String, Object> sourceDataMap = new HashMap<String, Object>(personnelInfoMap);
            try {

                //判断必填项
                if(personnelInfoMap.get("name") != null && StringUtil.isNotBlank(String.valueOf(personnelInfoMap.get("name")))) {

                }else{
                    sourceDataMap.put("ERROR_MSG","姓名为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                if(personnelInfoMap.get("idType") != null && StringUtil.isNotBlank(String.valueOf(personnelInfoMap.get("idType")))) {
                }else{
                    sourceDataMap.put("ERROR_MSG","证件类型为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                if(personnelInfoMap.get("idNumber") != null && StringUtil.isNotBlank(String.valueOf(personnelInfoMap.get("idNumber")))) {
                }else{
                    sourceDataMap.put("ERROR_MSG","证件号码为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                if(personnelInfoMap.get("isEnterSite") != null && StringUtil.isNotBlank(String.valueOf(personnelInfoMap.get("isEnterSite")))) {
                }else{
                    sourceDataMap.put("ERROR_MSG","是否进入工地为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                //判断是否进入工地
                if(personnelInfoMap.get("isEnterSite") != null && StringUtil.isNotBlank(String.valueOf(personnelInfoMap.get("isEnterSite")))) {
                    String isEnterSite = personnelInfoMap.get("isEnterSite").toString();
                    if (isEnterSite.equalsIgnoreCase("是"))
                        personnelInfoMap.put("isEnterSite",1);
                    else if (isEnterSite.equalsIgnoreCase("否"))
                        personnelInfoMap.put("isEnterSite",0);
                    else
                    {
                        sourceDataMap.put("ERROR_MSG","是否进入工地填写不正确(是/否)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }
                //判断性别
                if(personnelInfoMap.get("sex") != null && StringUtil.isNotBlank(String.valueOf(personnelInfoMap.get("sex")))) {
                    String sex = personnelInfoMap.get("sex").toString();
                    if (sex.equalsIgnoreCase("男"))
                        personnelInfoMap.put("sex",1);
                    else if (sex.equalsIgnoreCase("女"))
                        personnelInfoMap.put("sex",0);
                    else
                    {
                        sourceDataMap.put("ERROR_MSG","性别填写不正确(男/女)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }
                //判断出生日期
                if(personnelInfoMap.get("birthday") != null && StringUtil.isNotBlank(String.valueOf(personnelInfoMap.get("birthday")))) {
                    String birthday = personnelInfoMap.get("birthday").toString();
                    boolean res = TimeUtil.isValidDate(birthday);
                    if(res == false){
                        sourceDataMap.put("ERROR_MSG","出生日期填写不正确(格式YYYY-MM-DD)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }
                //判断证件类型
                if(personnelInfoMap.get("idType") != null && StringUtil.isNotBlank(String.valueOf(personnelInfoMap.get("idType")))) {
                    personnelInfoMap.put("PARENT_CODE", "ID_TYPE");
                    personnelInfoMap.put("DICT_VALUE", personnelInfoMap.get("idType"));
                    List<SysDict> workTypeList = sysDictService.getAllSysDict(personnelInfoMap);
                    if (workTypeList != null && workTypeList.size() > 0) {
                        SysDict dict = workTypeList.get(0);
                        personnelInfoMap.put("idType", dict.getCode());
                    } else {
                        sourceDataMap.put("ERROR_MSG","证件类型填写不正确(参考数据字典)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }
                //判断证件有效截止期
                if(personnelInfoMap.get("idInvalidTime") != null && StringUtil.isNotBlank(String.valueOf(personnelInfoMap.get("idInvalidTime")))) {
                    String idInvalidTime = personnelInfoMap.get("idInvalidTime").toString();
                    boolean res = TimeUtil.isValidDate(idInvalidTime);
                    if(res == false){
                        sourceDataMap.put("ERROR_MSG","证件有效截止期填写不正确(格式YYYY-MM-DD)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }
                //判断政治面貌
                if(personnelInfoMap.get("politicalStatus") != null && StringUtil.isNotBlank(String.valueOf(personnelInfoMap.get("politicalStatus")))) {
                    personnelInfoMap.put("PARENT_CODE", "POLITICAL_STATUS");
                    personnelInfoMap.put("DICT_VALUE", personnelInfoMap.get("politicalStatus"));
                    List<SysDict> workTypeList = sysDictService.getAllSysDict(personnelInfoMap);
                    if (workTypeList != null && workTypeList.size() > 0) {
                        SysDict dict = workTypeList.get(0);
                        personnelInfoMap.put("politicalStatus", dict.getCode());
                    } else {
                        sourceDataMap.put("ERROR_MSG","政治面貌填写不正确(参考数据字典)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }
                //判断婚姻状况
                if(personnelInfoMap.get("maritalStatus") != null && StringUtil.isNotBlank(String.valueOf(personnelInfoMap.get("maritalStatus")))) {
                    String maritalStatus = personnelInfoMap.get("maritalStatus").toString();
                    if (maritalStatus.equalsIgnoreCase("未婚"))
                        personnelInfoMap.put("maritalStatus",0);
                    else if (maritalStatus.equalsIgnoreCase("已婚"))
                        personnelInfoMap.put("maritalStatus",1);
                    else
                    {
                        sourceDataMap.put("ERROR_MSG","婚姻状况填写不正确(未婚/已婚)");
                        failedList.add(sourceDataMap);
                        continue;
                    }

                }
                //判断学历
                if(personnelInfoMap.get("education") != null && StringUtil.isNotBlank(String.valueOf(personnelInfoMap.get("education")))) {
                    personnelInfoMap.put("PARENT_CODE", "EDUCATION_LEVEL");
                    personnelInfoMap.put("DICT_VALUE", personnelInfoMap.get("education"));
                    List<SysDict> educationList = sysDictService.getAllSysDict(personnelInfoMap);
                    if (educationList != null && educationList.size() > 0) {
                        SysDict dict = educationList.get(0);
                        personnelInfoMap.put("education", dict.getCode());
                    } else {
                        sourceDataMap.put("ERROR_MSG","学历填写不正确(参考数据字典)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }
                //岗位
                if(personnelInfoMap.get("workType") != null && StringUtil.isNotBlank(String.valueOf(personnelInfoMap.get("workType")))) {
                    personnelInfoMap.put("PARENT_CODE", "WORK_TYPE");
                    personnelInfoMap.put("DICT_VALUE", personnelInfoMap.get("workType"));
                    List<SysDict> workTypeList = sysDictService.getAllSysDict(personnelInfoMap);
                    if (workTypeList != null && workTypeList.size() > 0) {
                        SysDict dict = workTypeList.get(0);
                        personnelInfoMap.put("workType", dict.getCode());
                    } else {
                        sourceDataMap.put("ERROR_MSG","岗位填写不正确(参考数据字典)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }
                // 所属单位
                if(personnelInfoMap.get("company") != null && StringUtil.isNotBlank(String.valueOf(personnelInfoMap.get("company")))) {
                    String company = String.valueOf(personnelInfoMap.get("company"));
                    personnelInfoMap.put("DEPT_NAME",company);
                    List<Map<String, String>> deptList = deptService.getDeptCDByName(personnelInfoMap);
                    if (deptList != null && deptList.size() > 0) {
                        Map<String, String> deptMap = deptList.get(0);
                        personnelInfoMap.put("company", deptMap.get("DEPT_CD"));
                    } else {
                        sourceDataMap.put("ERROR_MSG","所属单位填写不正确(参考用户管理)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }
                //判断是否办理居住证
                if(personnelInfoMap.get("isResidence") != null && StringUtil.isNotBlank(String.valueOf(personnelInfoMap.get("isResidence")))) {
                    String isResidence = personnelInfoMap.get("isResidence").toString();
                    if (isResidence.equalsIgnoreCase("是"))
                        personnelInfoMap.put("isResidence",1);
                    else if (isResidence.equalsIgnoreCase("否"))
                        personnelInfoMap.put("isResidence",0);
                    else{
                        sourceDataMap.put("ERROR_MSG","是否办理居住证填写不正确(是/否)");
                        failedList.add(sourceDataMap);
                        continue;
                    }

                }
                //判断入场日期
                if(personnelInfoMap.get("inDate") != null && StringUtil.isNotBlank(String.valueOf(personnelInfoMap.get("inDate")))) {
                    String inDate = personnelInfoMap.get("inDate").toString();
                    boolean res = TimeUtil.isValidDate(inDate);
                    if(res == false){
                        sourceDataMap.put("ERROR_MSG","入场日期填写不正确(格式YYYY-MM-DD)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }
                //判断出场日期
                if(personnelInfoMap.get("outDate") != null && StringUtil.isNotBlank(String.valueOf(personnelInfoMap.get("outDate")))) {
                    String outDate = personnelInfoMap.get("outDate").toString();
                    boolean res = TimeUtil.isValidDate(outDate);
                    if(res == false){
                        sourceDataMap.put("ERROR_MSG","出场日期填写不正确(格式YYYY-MM-DD)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }
                //判断证书类型
                if(certificateMap.get("certificateType") != null && StringUtil.isNotBlank(String.valueOf(certificateMap.get("certificateType")))) {
                    certificateMap.put("PARENT_CODE", "CERTIFICATE_TYPE");
                    certificateMap.put("DICT_VALUE", certificateMap.get("certificateType"));
                    List<SysDict> certificateTypeList = sysDictService.getAllSysDict(certificateMap);
                    if (certificateTypeList != null && certificateTypeList.size() > 0) {
                        SysDict dict = certificateTypeList.get(0);
                        certificateMap.put("certificateType", dict.getCode());
                    } else {
                        sourceDataMap.put("ERROR_MSG","证书类型填写不正确(参考数据字典)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }
                //判断证书有效期
                if(certificateMap.get("effectiveEndDate") != null && StringUtil.isNotBlank(String.valueOf(certificateMap.get("effectiveEndDate")))) {
                    String effectiveEndDate = certificateMap.get("effectiveEndDate").toString();
                    boolean res = TimeUtil.isValidDate(effectiveEndDate);
                    if(res == false){
                        sourceDataMap.put("ERROR_MSG","证书有效期填写不正确(格式YYYY-MM-DD)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }




                Map<String, Object> paramMap = new HashMap<String, Object>();
                //paramMap.put("name",personnelInfoMap.get("name"));
                paramMap.put("idNumberExcel",personnelInfoMap.get("idNumber"));
                paramMap.put("userId",userId);
                //paramMap.put("idType",personnelInfoMap.get("idType"));
                List<Map<String, Object>>  personnelList =  this.getPersonnelInfoListNoPage(paramMap);
                if (personnelList != null && personnelList.size() > 0)
                {
                    if(personnelList.size() > 1){
                        sourceDataMap.put("ERROR_MSG","数据库中存在"+personnelList.size()+"条证件号相同的数据，请先手动删除至一条后再进行导入");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                    String tempName = personnelList.get(0).get("name").toString();
                    if (!tempName.equalsIgnoreCase(personnelInfoMap.get("name").toString()))
                    {
                        sourceDataMap.put("ERROR_MSG","姓名不能修改");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                    String certificateId = personnelList.get(0).get("certificateId")==null?"":personnelList.get(0).get("certificateId").toString();
                    if (certificateId.length() == 0)
                    {
                        certificateMap.put("personnelId",personnelList.get(0).get("id"));
                        certificateService.insertCertificate(certificateMap);
                    }else
                    {
                        certificateMap.put("id",certificateId);
                        certificateService.updateCertificate(certificateMap);
                    }
                    personnelInfoMap.put("uploader",userId);
                    personnelInfoMap.put("id",personnelList.get(0).get("id"));
                    personnelInfoMapper.updatePersonnelInfo(personnelInfoMap);
                    updateList.add(personnelInfoMap);
                }
                else {
                    personnelInfoMap.put("creator",userId);
                    personnelInfoMapper.insertPersonnelInfo(personnelInfoMap);
                    certificateMap.put("personnelId",personnelInfoMap.get("id"));
                    certificateService.insertCertificate(certificateMap);
                    successList.add(personnelInfoMap);
                }

            }catch (Exception e){
                String errorMsg = e.getMessage();
                if(errorMsg.indexOf("###",10) != -1){
                    errorMsg = errorMsg.substring(0,errorMsg.indexOf("###",10));
                }
                sourceDataMap.put("ERROR_MSG",errorMsg);
                //记录导入失败记录
                failedList.add(sourceDataMap);
            }
        }

        //组装本次导入的结果
        resultMap.put(Constant.IMPORT_HE_SUCCESS,successList);
        resultMap.put(Constant.IMPORT_HE_IGNORE,ignoreList);
        resultMap.put(Constant.IMPORT_HE_FAILED,failedList);
        resultMap.put(Constant.IMPORT_HE_UPDATED,updateList);
        return resultMap;
    }

    public Map<String, String> getFieldMap(){
        Map<String, String> fieldMapping = new LinkedHashMap<>();

        fieldMapping.put("name","姓名");
        fieldMapping.put("sex","性别");
        fieldMapping.put("birthday","出生日期");
        fieldMapping.put("nation","民族");
        fieldMapping.put("idType","证件类型");
        fieldMapping.put("idNumber","证件号码");
        fieldMapping.put("idInvalidTime","证件有效截止期");
        fieldMapping.put("politicalStatus","政治面貌");
        fieldMapping.put("maritalStatus","婚姻状况");
        fieldMapping.put("censusRegisterAddress","户籍地址");
        fieldMapping.put("education","学历");
        fieldMapping.put("address","本市暂住地址");
        fieldMapping.put("tel","本地联系电话");
        fieldMapping.put("workType","岗位");
        fieldMapping.put("company","所属单位");
        fieldMapping.put("isResidence","是否办理居住证");
        fieldMapping.put("isEnterSite","是否进入工地");
        fieldMapping.put("inDate","入场日期");
        fieldMapping.put("outDate","出场日期");

        fieldMapping.put("number","证书编号");
        fieldMapping.put("certificateName","证书名称");
        fieldMapping.put("certificateType","证书类型");
        fieldMapping.put("issueName","发证单位");
        fieldMapping.put("effectiveEndDate","证书有效期");

        return fieldMapping;
    }

    public Map<String, String> getLogMap(){
        Map<String, String> fieldMapping = new LinkedHashMap<>();

//        fieldMapping.put("name","姓名");
//        fieldMapping.put("sex","性别");
//        fieldMapping.put("birthday","出生日期");
//        fieldMapping.put("nation","民族");
//        fieldMapping.put("idTypeName","证件类型");
//        fieldMapping.put("idNumber","证件号码");
//        fieldMapping.put("idInvalidTime","证件有效截止期");
//        fieldMapping.put("politicalStatusName","政治面貌");
//        fieldMapping.put("maritalStatus","婚姻状况");
//        fieldMapping.put("censusRegisterAddress","户籍地址");
//        fieldMapping.put("educationName","学历");
//        fieldMapping.put("address","本市暂住地址");
//        fieldMapping.put("tel","本地联系电话");
//        fieldMapping.put("workTypeName","岗位");
//        fieldMapping.put("companyName","所属单位");
//        fieldMapping.put("isResidence","是否办理居住证");
//        fieldMapping.put("isEnterSite","是否进入工地");
//        fieldMapping.put("inDate","入场日期");
//        fieldMapping.put("outDate","出场日期");
//        fieldMapping.put("lastPhysicalDate","上次体检日期");
//        fieldMapping.put("lastPhysicalResultName","上次体检结果");
//        fieldMapping.put("lastTrainDate","上次培训日期");
//        fieldMapping.put("lastTrainScore","上次培训成绩");
//        fieldMapping.put("trainTime","培训总时间(小时)");
//        fieldMapping.put("isUploadZjj","是否上报住建局");

        fieldMapping.put("name","姓名");
        fieldMapping.put("sex","性别");
        fieldMapping.put("birthday","出生日期");
        fieldMapping.put("nation","民族");
        fieldMapping.put("idTypeName","证件类型");
        fieldMapping.put("idNumber","证件号码");
        fieldMapping.put("idInvalidTime","证件有效截止期");
        fieldMapping.put("politicalStatusName","政治面貌");
        fieldMapping.put("maritalStatus","婚姻状况");
        fieldMapping.put("censusRegisterAddress","户籍地址");
        fieldMapping.put("educationName","学历");
        fieldMapping.put("address","本市暂住地址");
        fieldMapping.put("tel","本地联系电话");
        fieldMapping.put("workTypeName","岗位");
        fieldMapping.put("deptName","所属单位");
        fieldMapping.put("isResidence","是否办理居住证");
        fieldMapping.put("isEnterSite","是否进入工地");
        fieldMapping.put("inDate","入场日期");
        fieldMapping.put("outDate","出场日期");

        fieldMapping.put("number","证书编号");
        fieldMapping.put("certificateName","证书名称");
        fieldMapping.put("certificateTypeName","证书类型");
        fieldMapping.put("issueName","发证单位");
        fieldMapping.put("effectiveEndDate","证书有效期");

        return fieldMapping;
    }

    public List<Map<String, Object>> getPersonnelLog() {
        List<Map<String, Object>> personnelInfoList = personnelInfoMapper.getPersonnelExcel();
        if (personnelInfoList != null)
        {
           for(int i=0;i<personnelInfoList.size();i++){
               Map<String, Object> personMap = new HashMap<>();
               personMap = personnelInfoList.get(i);
               String sex = personMap.get("sex")==null?"":personMap.get("sex").toString();
               if(sex.equalsIgnoreCase("0")){
                   personMap.put("sex","女");
               }else if(sex.equalsIgnoreCase("1")){
                   personMap.put("sex","男");
               }
               String isResidence = personMap.get("isResidence")==null?"":personMap.get("isResidence").toString();
               if(isResidence.equalsIgnoreCase("0")){
                   personMap.put("isResidence","否");
               }else if(isResidence.equalsIgnoreCase("1")){
                   personMap.put("isResidence","是");
               }
               String isEnterSite = personMap.get("isEnterSite")==null?"":personMap.get("isEnterSite").toString();
               if(isEnterSite.equalsIgnoreCase("0")){
                   personMap.put("isEnterSite","否");
               }else if(isEnterSite.equalsIgnoreCase("1")){
                   personMap.put("isEnterSite","是");
               }
               String maritalStatus = personMap.get("maritalStatus")==null?"":personMap.get("maritalStatus").toString();
               if(maritalStatus.equalsIgnoreCase("0")){
                   personMap.put("maritalStatus","未婚");
               }else if(maritalStatus.equalsIgnoreCase("1")){
                   personMap.put("maritalStatus","已婚");
               }
               String isUploadZjj = personMap.get("isUploadZjj")==null?"":personMap.get("isUploadZjj").toString();
               if(isUploadZjj.equalsIgnoreCase("0")){
                   personMap.put("isUploadZjj","否");
               }else if(isUploadZjj.equalsIgnoreCase("1")){
                   personMap.put("isUploadZjj","是");
               }
           }
        }
        return personnelInfoList;
    }

    /**
     * 向小麦注册用户信息
     * @param personId 人员ID可以为空，如果为空，则自动生成32 GUID，可写
     * @param idNumber 卡号，人脸识别没有卡，则可以传身份证号，可写
     * @param name 人员名称，必填
     * @return
     */
    public  String personnelCreateToOtherSystem(String personnelId,String personId,String idNumber,String name,String paramIp,String creator,String paramSiteId)
    {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("id",personId==null?"":personId);
        paramMap.put("idcardNum",idNumber==null?"":idNumber);
        paramMap.put("name",name==null?"":name);
        Gson gson = new Gson();
        String person = gson.toJson(paramMap);
        List<Map<String, Object>>  gatherEquipList = gatherEquipService.getPeopleGatherEquipListOfSite(paramSiteId);
        String result = "";
        logger.info("开始向人脸识别设备注册人员信息");
        for (int i = 0; i < gatherEquipList.size(); i++) {//循环同步进入闸机记录
            Map<String, Object> gatherEquipMap = gatherEquipList.get(i);
            String password = gatherEquipMap.get("password")==null?"":gatherEquipMap.get("password").toString();
            String ip = gatherEquipMap.get("ip").toString();
            String siteId = gatherEquipMap.get("siteId").toString();
            if (!ip.equalsIgnoreCase(paramIp) && paramIp.length() > 0)
                continue;
            String url = PropertiesUtil.get("PersonnelCreateUrl");
            url = url.replace("{ip}",ip);
            //String param = "pass="+password+"&person="+person;
            String contentType = "application/x-www-form-urlencoded";
            logger.info("向第"+(i+1)+"个（"+ip+"）（"+ip+"）人脸识别设备注册人员信息");
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("pass",password);
            map.put("person",person);
            String resultStr = HttpUtil.sendPost(url,map,contentType);
            if (resultStr.length() == 0)
            {
                logger.info("访问人脸识别服务器失败，向第"+(i+1)+"个（"+ip+"）人脸设备注册人员信息失败，请检测网络或人脸识别设备服务器是否正常");
                result = StringUtil.splitJoint(result,"访问人脸识别服务器失败，向第"+(i+1)+"个（"+ip+"）人脸设备注册人员信息失败,请检测网络或人脸识别设备服务器是否正常，然后再次注册！");

                //return result;
            }else
            {
                JsonObject returnData = new JsonParser().parse(resultStr).getAsJsonObject();
                String success = returnData.get("success").getAsString();
                if(success.equalsIgnoreCase("true"))//调用结果成功
                {
                    //result = returnData.getAsJsonObject("data").get("id").getAsString();
                    personnelGatherEquipService.insertPersonnelGatherEquipEx(personnelId,gatherEquipMap.get("id").toString(),"1",creator,siteId);
                    logger.info("第"+(i+1)+"个（"+ip+"）人脸识别设备注册成功");

                }else
                {
                    String msg = returnData.get("msg").getAsString();
                    logger.info("人脸识别第"+(i+1)+"个（"+ip+"）设备注册人员信息失败！错误信息："+msg);
                    result = StringUtil.splitJoint(result,"人脸识别第"+(i+1)+"个（"+ip+"）设备注册人员信息失败！错误信息："+msg);
                }
            }


        }
        return result;
    }

    /**
     * 向小麦注册用户信息
     * @param personId 人员ID可以为空，如果为空，则自动生成32 GUID，可写
     * @param idNumber 卡号，人脸识别没有卡，则可以传身份证号，可写
     * @param name 人员名称，必填
     * @return
     */
    public  String personnelCreateToOtherSystemByIp(String personnelId,String personId,String idNumber,String name,String ip,String password,String gatherEquipId,String creator,String siteId)
    {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("id",personId==null?"":personId);
        paramMap.put("idcardNum",idNumber==null?"":idNumber);
        paramMap.put("name",name==null?"":name);
        Gson gson = new Gson();
        String person = gson.toJson(paramMap);

        String result = "";
        logger.info("开始向人脸识别设备注册人员信息");
        String url = PropertiesUtil.get("PersonnelCreateUrl");
        url = url.replace("{ip}",ip);
        //String param = "pass="+password+"&person="+person;
        String contentType = "application/x-www-form-urlencoded";
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("pass",password);
        map.put("person",person);
        String resultStr = HttpUtil.sendPost(url,map,contentType);
        if (resultStr.length() == 0)
        {
            logger.info("访问人脸识别服务器失败，向"+ip+"设备注册人员信息失败，请检测网络或人脸识别设备服务器是否正常");
            result = StringUtil.splitJoint(result,"访问人脸识别服务器失败，向"+ip+"设备注册人员信息失败,请检测网络或人脸识别设备服务器是否正常，然后再次注册！");

            //return result;
        }else
        {
            JsonObject returnData = new JsonParser().parse(resultStr).getAsJsonObject();
            String success = returnData.get("success").getAsString();
            if(success.equalsIgnoreCase("true"))//调用结果成功
            {
                result = returnData.getAsJsonObject("data").get("id").getAsString();
                personnelGatherEquipService.insertPersonnelGatherEquipEx(personnelId,gatherEquipId,"1",creator,siteId);
                logger.info("向"+ip+"个（"+ip+"）人脸识别设备注册成功");

            }else
            {
                String msg = returnData.get("msg").getAsString();
                logger.info("向"+ip+"设备注册人员信息失败！错误信息："+msg);
                result = StringUtil.splitJoint(result,"向"+ip+"设备注册人员信息失败！错误信息："+msg);
            }
        }

        return result;
    }

    /**
     * 向小麦更新用户信息
     * @param personId 人员ID可以为空，如果为空，则自动生成32 GUID，可写
     * @param idNumber 卡号，人脸识别没有卡，则可以传身份证号，可写
     * @param name 人员名称，必填
     * @return
     */
    public  String personnelUpdateToOtherSystem(String personId,String idNumber,String name,String paramIp)
    {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("id",personId==null?"":personId);
        paramMap.put("idcardNum",idNumber==null?"":idNumber);
        paramMap.put("name",name==null?"":name);
        Gson gson = new Gson();
        String person = gson.toJson(paramMap);
        List<Map<String, Object>>  gatherEquipList = gatherEquipService.getPeopleGatherEquipList();
        String result = "";
        logger.info("开始向人脸识别设备更新人员信息");
        for (int i = 0; i < gatherEquipList.size(); i++) {//循环同步进入闸机记录

            Map<String, Object> gatherEquipMap = gatherEquipList.get(i);
            String password = gatherEquipMap.get("password")==null?"":gatherEquipMap.get("password").toString();
            String ip = gatherEquipMap.get("ip").toString();
            if (!ip.equalsIgnoreCase(paramIp) && paramIp.length() > 0)
                continue;
            String url = PropertiesUtil.get("PersonnelUpdateUrl");
            url = url.replace("{ip}",ip);
            //String param = "pass="+password+"&person="+person;
            String contentType = "application/x-www-form-urlencoded";
            logger.info("向第"+(i+1)+"个（"+ip+"）人脸识别设备更新人员信息");
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("pass",password);
            map.put("person",person);
            String resultStr = HttpUtil.sendPost(url,map,contentType);
            if (resultStr.length() == 0)
            {
                logger.info("访问人脸识别服务器失败，向第"+(i+1)+"个（"+ip+"）人脸设备更新人员信息失败，请检测网络或人脸识别设备服务器是否正常");
                result = StringUtil.splitJoint(result,"访问人脸识别服务器失败，向第"+(i+1)+"个（"+ip+"）人脸设备更新人员信息失败,请检测网络或人脸识别设备服务器是否正常，然后再次更新！");

            }else
            {
                JsonObject returnData = new JsonParser().parse(resultStr).getAsJsonObject();
                String success = returnData.get("success").getAsString();
                if(success.equalsIgnoreCase("true"))//调用结果成功
                {
                    result = returnData.getAsJsonObject("data").get("id").getAsString();
                    logger.info("第"+(i+1)+"个（"+ip+"）人脸识别设备更新成功");

                }else
                {
                    String msg = returnData.get("msg").getAsString();
                    logger.info("人脸识别第"+(i+1)+"个（"+ip+"）设备更新人员信息失败！错误信息："+msg);
                    result = StringUtil.splitJoint(result,"人脸识别第"+(i+1)+"个（"+ip+"）设备更新人员信息失败！错误信息："+msg);
                }
            }


        }
        return result;
    }

    /**
     * 向人脸识别删除用户
     * @param personId 人员ID可以为空，如果为空，则自动生成32 GUID，可写
     * @return
     */
    public  String personnelDeleteToOtherSystem(String personnelId,String personId,String paramIp,String paramSiteId)
    {
        //List<Map<String, Object>>  gatherEquipList = gatherEquipService.getPeopleGatherEquipList();
        List<Map<String, Object>>  gatherEquipList = gatherEquipService.getPeopleGatherEquipListOfSite(paramSiteId);
        String result = "";
        logger.info("开始向人脸识别设备删除人员信息");
        for (int i = 0; i < gatherEquipList.size(); i++) {//循环同步进入闸机记录

            Map<String, Object> gatherEquipMap = gatherEquipList.get(i);
            String password = gatherEquipMap.get("password")==null?"":gatherEquipMap.get("password").toString();
            String ip = gatherEquipMap.get("ip").toString();
            String siteId = gatherEquipMap.get("siteId").toString();
            if (!ip.equalsIgnoreCase(paramIp) && paramIp.length() > 0)
                continue;
            String url = PropertiesUtil.get("PersonnelDeleteUrl");
            url = url.replace("{ip}",ip);
            //String param = "pass="+password+"&id="+personId;
            String contentType = "application/x-www-form-urlencoded";
            logger.info("向第"+(i+1)+"个（"+ip+"）人脸识别设备删除人员信息");
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("pass",password);
            map.put("id",personId);
            String resultStr = HttpUtil.sendPost(url,map,contentType);
            if (resultStr.length() == 0)
            {
                logger.info("访问人脸识别服务器失败，向第"+(i+1)+"个（"+ip+"）人脸设备删除人员信息失败，请检测网络或人脸识别设备服务器是否正常");
                result = StringUtil.splitJoint(result,"访问人脸识别服务器失败，向第"+(i+1)+"个（"+ip+"）人脸设备删除人员信息失败,请检测网络或人脸识别设备服务器是否正常！");

            }else{
                JsonObject returnData = new JsonParser().parse(resultStr).getAsJsonObject();
                String success = returnData.get("success").getAsString();
                if(success.equalsIgnoreCase("true"))//调用结果成功
                {
                    logger.info("第"+(i+1)+"个（"+ip+"）人脸识别设备删除成功");
                    personnelGatherEquipService.deletePersonnelGatherEquipByIds(personnelId,gatherEquipMap.get("id").toString(),siteId);

                }else
                {
                    String msg = returnData.get("msg").getAsString();
                    logger.info("人脸识别第"+(i+1)+"个（"+ip+"）设备删除人员信息失败！错误信息："+msg);
                    result = StringUtil.splitJoint(result,"人脸识别第"+(i+1)+"个（"+ip+"）设备删除人员信息失败！错误信息："+msg);
                }
            }

        }
        return result;
    }




    /**
     * 向小麦注册照片信息
     * @param personId 人员ID，不可为空
     * @param faceId 照片ID可以为空，如果为空，则自动生成32 GUID，可写
     * @param imgBase64 照片bse64，必填
     * @return
     */
    public  String faceCreateToOtherSystem(String personnelId,String personId,String faceId,String imgBase64,String paramIp,String creator,String paramSiteId)
    {
        /*Map<String, String> paramMap = new HashMap<>();
        paramMap.put("personId",personId==null?"":personId);
        paramMap.put("idcardNum",faceId==null?"":faceId);
        paramMap.put("imgBase64",imgBase64==null?"":imgBase64   );
        Gson gson = new Gson();
        String person = gson.toJson(paramMap);*/
        //List<Map<String, Object>>  gatherEquipList = gatherEquipService.getPeopleGatherEquipList();
        List<Map<String, Object>>  gatherEquipList = gatherEquipService.getPeopleGatherEquipListOfSite(paramSiteId);
        String result = "";
        logger.info("开始向人脸识别设备注册照片信息");
        for (int i = 0; i < gatherEquipList.size(); i++) {//循环同步进入闸机记录

            Map<String, Object> gatherEquipMap = gatherEquipList.get(i);
            String password = gatherEquipMap.get("password")==null?"":gatherEquipMap.get("password").toString();
            String ip = gatherEquipMap.get("ip").toString();
            String siteId = gatherEquipMap.get("siteId").toString();
            if (!ip.equalsIgnoreCase(paramIp) && paramIp.length() > 0)
                continue;
            String url = PropertiesUtil.get("FaceCreateUrl");
            url = url.replace("{ip}",ip);
            //String param = "pass="+password+"&personId="+personId+"&faceId="+faceId+"&imgBase64="+imgBase64;
            String contentType = "application/x-www-form-urlencoded";
            logger.info("向第"+(i+1)+"个（"+ip+"）人脸设备注册照片信息");
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("pass",password);
            map.put("personId",personId);
            map.put("faceId",faceId);
            map.put("imgBase64",imgBase64);
            String resultStr = HttpUtil.sendPost(url,map,contentType);
            if (resultStr.length() == 0)
            {
                logger.info("访问人脸识别服务器失败，向第"+(i+1)+"个（"+ip+"）人脸设备注册照片失败");
                result = StringUtil.splitJoint(result,"访问人脸识别服务器失败，向第"+(i+1)+"个（"+ip+"）人脸设备注册照片失败！");
                //return result;
            }else
            {
                JsonObject returnData = new JsonParser().parse(resultStr).getAsJsonObject();
                String success = returnData.get("success").getAsString();
                if(success.equalsIgnoreCase("true"))//调用结果成功
                {
                    //result = faceId;//returnData.get("data").getAsString();
                    personnelGatherEquipService.insertPersonnelGatherEquipEx(personnelId,gatherEquipMap.get("id").toString(),"2",creator,siteId);
                    logger.info("第"+(i+1)+"个（"+ip+"）人脸识别设备注册照片成功");

                }else
                {
                    String msg = returnData.get("msg").getAsString();
                    logger.info("人脸识别第"+(i+1)+"个（"+ip+"）设备注册照片失败！错误信息："+msg);
                    result = StringUtil.splitJoint(result,"人脸识别第"+(i+1)+"个（"+ip+"）设备注册照片失败！错误信息："+msg);
                }
            }


        }
        return result;
    }

    /**
     * 向小麦注册照片信息
     * @param personId 人员ID，不可为空
     * @param faceId 照片ID可以为空，如果为空，则自动生成32 GUID，可写
     * @param imgBase64 照片bse64，必填
     * @return
     */
    public  String faceCreateToOtherSystemByIp(String personnelId,String personId,String faceId,String imgBase64,String ip,String password,String gatherEquipId,String creator,String siteId)
    {
        /*Map<String, String> paramMap = new HashMap<>();
        paramMap.put("personId",personId==null?"":personId);
        paramMap.put("idcardNum",faceId==null?"":faceId);
        paramMap.put("imgBase64",imgBase64==null?"":imgBase64   );
        Gson gson = new Gson();
        String person = gson.toJson(paramMap);*/
        String result = "";
        logger.info("开始向人脸识别设备"+ip+"注册照片信息");
        String url = PropertiesUtil.get("FaceCreateUrl");
        url = url.replace("{ip}",ip);
        //String param = "pass="+password+"&personId="+personId+"&faceId="+faceId+"&imgBase64="+imgBase64;
        String contentType = "application/x-www-form-urlencoded";
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("pass",password);
        map.put("personId",personId);
        map.put("faceId",faceId);
        map.put("imgBase64",imgBase64);
        String resultStr = HttpUtil.sendPost(url,map,contentType);
        if (resultStr.length() == 0)
        {
            logger.info("访问人脸识别服务器失败，向"+ip+"设备注册照片失败");
            result = StringUtil.splitJoint(result,"访问人脸识别服务器失败，向"+ip+"设备注册照片失败！");
            //return result;
        }else{
            JsonObject returnData = new JsonParser().parse(resultStr).getAsJsonObject();
            String success = returnData.get("success").getAsString();
            if(success.equalsIgnoreCase("true"))//调用结果成功
            {
                result = faceId;//returnData.get("data").getAsString();
                personnelGatherEquipService.insertPersonnelGatherEquipEx(personnelId,gatherEquipId,"2",creator,siteId);
                logger.info("向"+ip+"人脸识别设备注册照片成功");

            }else
            {
                String msg = returnData.get("msg").getAsString();
                logger.info("人脸识别"+ip+"设备注册照片失败！错误信息："+msg);
                result = StringUtil.splitJoint(result,"人脸识别"+ip+"设备注册照片失败！错误信息："+msg);
            }
        }

        return result;
    }

    /**
     * 向小麦更新用户信息
     * @param personId 人员ID，不可为空
     * @param faceId 照片ID可以为空，如果为空，则自动生成32 GUID，可写
     * @param imgBase64 照片bse64，必填
     * @return
     */
    public  String faceUpdateToOtherSystem(String personId,String faceId,String imgBase64,String paramIp,String siteId)
    {
        /*Map<String, String> paramMap = new HashMap<>();
        paramMap.put("personId",personId==null?"":personId);
        paramMap.put("idcardNum",faceId==null?"":faceId);
        paramMap.put("imgBase64",imgBase64==null?"":imgBase64   );
        Gson gson = new Gson();
        String person = gson.toJson(paramMap);*/
        //List<Map<String, Object>>  gatherEquipList = gatherEquipService.getPeopleGatherEquipList();
        List<Map<String, Object>>  gatherEquipList = gatherEquipService.getPeopleGatherEquipListOfSite(siteId);
        String result = "";
        logger.info("开始向人脸识别设备更新照片信息");
        for (int i = 0; i < gatherEquipList.size(); i++) {//循环同步进入闸机记录

            Map<String, Object> gatherEquipMap = gatherEquipList.get(i);
            String password = gatherEquipMap.get("password")==null?"":gatherEquipMap.get("password").toString();
            String ip = gatherEquipMap.get("ip").toString();
            if (!ip.equalsIgnoreCase(paramIp) && paramIp.length() > 0)
                continue;
            String url = PropertiesUtil.get("FaceUpdateUrl");
            url = url.replace("{ip}",ip);
            //String param = "pass="+password+"&personId="+personId+"&faceId="+faceId+"&imgBase64="+imgBase64;
            String contentType = "application/x-www-form-urlencoded";
            logger.info("向第"+(i+1)+"个（"+ip+"）人脸设备更新照片信息");
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("pass",password);
            map.put("personId",personId);
            map.put("faceId",faceId);
            map.put("imgBase64",imgBase64);
            String resultStr = HttpUtil.sendPost(url,map,contentType);
            if (resultStr.length() == 0)
            {
                logger.info("访问人脸识别服务器失败，向第"+(i+1)+"个（"+ip+"）人脸设备更新照片失败");
                result = StringUtil.splitJoint(result,"访问人脸识别服务器失败，向第"+(i+1)+"个（"+ip+"）人脸设备更新照片失败！");
                //return result;
            }else
            {
                JsonObject returnData = new JsonParser().parse(resultStr).getAsJsonObject();
                String success = returnData.get("success").getAsString();
                if(success.equalsIgnoreCase("true"))//调用结果成功
                {
                    //result = faceId;//returnData.get("data").getAsString();
                    logger.info("第"+(i+1)+"个（"+ip+"）人脸识别设备更新成功");

                }else
                {
                    String msg = returnData.get("msg").getAsString();
                    logger.info("人脸识别第"+(i+1)+"个（"+ip+"）设备更新照片失败！错误信息："+msg);
                    result = StringUtil.splitJoint(result,"人脸识别第"+(i+1)+"个（"+ip+"）设备更新照片失败！错误信息："+msg);
                }
            }


        }
        return result;
    }

    /**
     * 根据用户id查找其管辖的车站
     * @param userId
     * @return
     */
    public String getSiteByUser(int userId){
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        List<Map<String,Object>> list = personnelInfoMapper.getSiteByUser(params);
        if (list == null || list.size() == 0)
            return null;
        String siteIds = null;
        for (int i = 0; i < list.size(); i++) {
            String siteId = list.get(i).get("SITE_ID").toString();
            if (siteIds == null)
                siteIds = siteId;
            else
                siteIds = siteIds + "," + siteId;
        }
        return siteIds;
    }

    public List<Map<String,Object>> getPersonBySite(Map<String,Object> params){
        return personnelInfoMapper.getPersonBySite(params);
    }

    public List<Map<String,Object>> getAllRectifyPerson(){
        return personnelInfoMapper.getAllRectifyPerson();
    }

    public void setAllRectifyPerson(HttpSession httpSession) {
        List<Map<String,Object>> rectifyPersonList = personnelInfoMapper.getAllRectifyPerson();
        if (rectifyPersonList == null || rectifyPersonList.size() == 0)
            return;
        httpSession.setAttribute("rectifyPersonList", rectifyPersonList);
    }

    public void updateWorker(Map<String,Object> params){

        personnelInfoMapper.updateResetZJJ(params);


        List<Map<String,Object>> workerList =  (List<Map<String,Object>>)params.get("workerList");
        logger.info("开始把每个工人的IS_UPLOAD_ZJJ更新为1-------------------"+workerList.size());
        for (int i = 0; i < workerList.size(); i++) {
            Map<String,Object> tempMap = workerList.get(i);
            personnelInfoMapper.updateWorker(tempMap);
        }
        logger.info("结束把每个工人的IS_UPLOAD_ZJJ更新为1-------------------");

    }
    
    public List<Map<String,Object>> getPersonnelByUser(Map<String, Object> params) {
		String sortColumn = "NAME"; //默认的排序列
		String sortType = "asc";
		String iSortCol_0 = (String) params.get("iSortCol_0");	//排序字段，前台传进来的为数值，列从0开始
		String sSortDir_0 = (String) params.get("sSortDir_0");	//排序类型，asc或desc
		if(StringUtil.isNotBlank(iSortCol_0) && StringUtil.isNotBlank(sSortDir_0)){
			sortColumn = (String) params.get("mDataProp_" + iSortCol_0);
			sortType = sSortDir_0;
		}
		String sortString = sortColumn + "." + sortType;	//排序字段及排序类型
		PageBounds pageBounds = new PageBounds(params, Order.formString(sortString));	//绑定排序及相关参数
		return getSqlSession().selectList("com.szgd.dao.ecdata.personnel.PersonnelInfoMapper.getPersonnelByUser", params,pageBounds);
	}

    public String importCertificate(Certificate certificate) throws Exception {
        String message = "";
        int allNum = 0;
        int successNum = 0;
        int errorNum = 0;
        List<String> errorMsg = new ArrayList<>();
        if(certificate != null){
            if(certificate.getCertificateAttach() != null){
                Map<String,Object> queryParam = new HashMap<>();
                Map<String,Object> attachParam = new HashMap<>();
                Map<String,Object> certificateParam = new HashMap<>();
                attachParam.put("source","ATTACH_CERTIFICATE");
                attachParam.put("type","ATTACH_PIC");
                attachParam.put("creator",certificate.getCreator());
                attachParam.put("path",SysUtil.getDateStr(null,"yyyyMM"));
                for(MultipartFile file : certificate.getCertificateAttach()){
                    allNum += 1;
                    String originalFileName = file.getOriginalFilename();
                    int index =  originalFileName.lastIndexOf(".");
                    String fileName = originalFileName.substring(0,index);
                    queryParam.put("fileName",fileName);
                    queryParam.put("userId",certificate.getUserId());
                    List<Map<String,Object>> personList = this.getPersonnelInfoListNoPage(queryParam);
                    if(personList != null && personList.size() > 0){
                        if(personList.size() == 1){
                            try{
                                String attachName = fileUtil.uploadPic(file.getInputStream(),originalFileName);
                                attachParam.put("name",attachName);
                                String personnelId = personList.get(0).get("id")==null?"":personList.get(0).get("id").toString();
                                String certificateId = personList.get(0).get("certificateId")==null?"":personList.get(0).get("certificateId").toString();
                                if(certificateId.length() > 0){
                                    attachParam.put("parentId",certificateId);
                                    Map<String,Object> certificateInfo = certificateService.getCertificate(certificateId);
                                    String attachId = certificateInfo.get("attachId")==null?"":certificateInfo.get("attachId").toString();
                                    if(attachId.length() > 0){
                                        attachParam.put("id",attachId);
                                        attachService.deleteAttach(attachParam);
                                        attachService.insertAttach(attachParam);
                                    }else{
                                        attachService.insertAttach(attachParam);
                                    }
                                }else{
                                    certificateParam.put("personnelId",personnelId);
                                    certificateParam.put("creator",certificate.getCreator());
                                    certificateService.insertCertificate(certificateParam);
                                    attachParam.put("parentId",certificateParam.get("id"));
                                    attachService.insertAttach(attachParam);
                                }
                                successNum += 1;
                            }catch (Exception e){
                                errorNum += 1;
                                errorMsg.add(originalFileName + "上传失败，服务器出错");
                            }
                        }else{
                            errorNum += 1;
                            errorMsg.add(originalFileName + "的姓名在数据库中存在重名现象，请对这些人员的证书照片进行手动上传");
                        }
                    }else{
                        errorNum += 1;
                        errorMsg.add(originalFileName + "的姓名在数据库中不存在，请检查命名是否准确");
                    }
                }
                message += "本次上传共处理<b>" + allNum
                        + "张</b>照片[<span style = 'color: green;font-weight: bold;'>成功："
                        + successNum + "张</span>，<span style = 'color: red;font-weight: bold;'>失败：" + errorNum + "张</span>]";
                if(errorNum > 0){
                    message += "</br><span style = 'font-weight: bold;'>失败条目如下：</span></br>";
                    for(int i = 0; i < errorMsg.size(); i++){
                        message += (i+1) + ". " + errorMsg.get(i) + "</br>";
                    }
                }

            }
        }
        return message;
    }

    public static void main(String[] args) {
        //System.out.println(new PersonnelInfoService().personnelCreateToOtherSystem("1","2","3"));
    }

}
